import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义一个商店管理系统的store (组合式API)
export const useShopStore = defineStore('shop-composition', () => {
  // state
  const products = ref([
    { id: 1, name: '笔记本电脑', price: 5999, inventory: 10 },
    { id: 2, name: '智能手机', price: 3999, inventory: 15 },
    { id: 3, name: '耳机', price: 899, inventory: 20 }
  ])
  
  const cart = ref([])
  
  const user = ref({
    id: null,
    name: '',
    isLoggedIn: false,
    points: 0
  })
  
  const orderHistory = ref([])
  
  // getters
  const cartItemCount = computed(() => {
    return cart.value.reduce((total, item) => total + item.quantity, 0)
  })
  
  const cartTotalPrice = computed(() => {
    return cart.value.reduce((total, item) => {
      const product = products.value.find(p => p.id === item.productId)
      return total + (product ? product.price * item.quantity : 0)
    }, 0)
  })
  
  const isAuthenticated = computed(() => {
    return user.value.isLoggedIn
  })
  
  // actions
  function addToCart(productId, quantity = 1) {
    // 检查商品是否存在
    const product = products.value.find(p => p.id === productId)
    if (!product) {
      throw new Error('商品不存在')
    }
    
    // 检查库存是否足够
    if (product.inventory < quantity) {
      throw new Error('库存不足')
    }
    
    // 查找购物车中是否已有该商品
    const cartItem = cart.value.find(item => item.productId === productId)
    
    if (cartItem) {
      // 如果购物车中已有该商品，增加数量
      cartItem.quantity += quantity
    } else {
      // 否则添加新商品到购物车
      cart.value.push({
        productId,
        quantity,
        addedAt: new Date()
      })
    }
    
    // 减少库存
    product.inventory -= quantity
    
    return { success: true, message: '已添加到购物车' }
  }
  
  function removeFromCart(productId, quantity = null) {
    const index = cart.value.findIndex(item => item.productId === productId)
    
    if (index === -1) {
      return { success: false, message: '购物车中没有该商品' }
    }
    
    const cartItem = cart.value[index]
    const product = products.value.find(p => p.id === productId)
    
    if (quantity === null || quantity >= cartItem.quantity) {
      // 如果没有指定数量或数量大于等于购物车中的数量，移除整个商品
      cart.value.splice(index, 1)
      
      // 恢复库存
      if (product) {
        product.inventory += cartItem.quantity
      }
    } else {
      // 否则减少数量
      cartItem.quantity -= quantity
      
      // 恢复库存
      if (product) {
        product.inventory += quantity
      }
    }
    
    return { success: true, message: '已从购物车移除' }
  }
  
  function clearCart() {
    // 恢复所有商品的库存
    cart.value.forEach(item => {
      const product = products.value.find(p => p.id === item.productId)
      if (product) {
        product.inventory += item.quantity
      }
    })
    
    // 清空购物车
    cart.value = []
    
    return { success: true, message: '购物车已清空' }
  }
  
  async function login(username, password) {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 简单的模拟登录逻辑，实际应用中应该调用API
    if (username && password) {
      user.value = {
        id: 1,
        name: username,
        isLoggedIn: true,
        points: 100
      }
      return { success: true, message: '登录成功' }
    } else {
      return { success: false, message: '用户名或密码不能为空' }
    }
  }
  
  function logout() {
    user.value = {
      id: null,
      name: '',
      isLoggedIn: false,
      points: 0
    }
    return { success: true, message: '已登出' }
  }
  
  async function checkout() {
    // 检查用户是否已登录
    if (!isAuthenticated.value) {
      return { success: false, message: '请先登录' }
    }
    
    // 检查购物车是否为空
    if (cart.value.length === 0) {
      return { success: false, message: '购物车为空' }
    }
    
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 创建订单
    const order = {
      id: Date.now(),
      userId: user.value.id,
      items: [...cart.value],
      totalAmount: cartTotalPrice.value,
      date: new Date(),
      status: 'completed'
    }
    
    // 添加到订单历史
    orderHistory.value.push(order)
    
    // 增加用户积分（假设消费1元获得0.1积分）
    user.value.points += Math.floor(cartTotalPrice.value * 0.1)
    
    // 清空购物车（但不恢复库存，因为已经购买了）
    cart.value = []
    
    return { 
      success: true, 
      message: '订单已完成', 
      order 
    }
  }
  
  return {
    // state
    products,
    cart,
    user,
    orderHistory,
    // getters
    cartItemCount,
    cartTotalPrice,
    isAuthenticated,
    // actions
    addToCart,
    removeFromCart,
    clearCart,
    login,
    logout,
    checkout
  }
})
